package com.cml.getway.core;

import com.cml.getway.common.constants.GetwayBufferHelper;
import com.cml.getway.core.netty.NettyHttpClient;
import com.cml.getway.core.netty.NettyHttpServer;
import com.cml.getway.core.netty.processor.NettyBatchEventProcessor;
import com.cml.getway.core.netty.processor.NettyCoreProcessor;
import com.cml.getway.core.netty.processor.NettyMpmcProcessor;
import com.cml.getway.core.netty.processor.NettyProcessor;
import lombok.extern.slf4j.Slf4j;

/**
 * 姓名：陈茂林
 * 时间：2023/12/20
 * 描述：
 */
@Slf4j
public class GetwayContainer implements LifeCycle{

    private GetwayConfig getwayConfig;

    private NettyProcessor nettyProcessor;

    private NettyHttpServer nettyHttpServer;

    private NettyHttpClient nettyHttpClient;

    public GetwayContainer( GetwayConfig getwayConfig){
        this.getwayConfig = getwayConfig;
        init();
    }
    @Override
    public void init() {
        NettyCoreProcessor nettyCoreProcessor = new NettyCoreProcessor();
        String bufferType = getwayConfig.getBufferType();
        if(GetwayBufferHelper.isFlusher(bufferType)){
            nettyProcessor= new NettyBatchEventProcessor(getwayConfig,nettyCoreProcessor);
        }else if(GetwayBufferHelper.isMpmc(bufferType)){
            nettyProcessor = new NettyMpmcProcessor(getwayConfig,nettyCoreProcessor,true);
        }else{
            nettyProcessor=nettyCoreProcessor;
        }
        nettyHttpServer= new NettyHttpServer(getwayConfig,nettyProcessor);
        nettyHttpClient=new NettyHttpClient(getwayConfig,nettyHttpServer.getEventLoopGroupWork());
    }

    @Override
    public void start() {
        nettyProcessor.start();
        nettyHttpServer.start();
        nettyHttpClient.start();
        log.info("容器启动完毕！");
    }

    @Override
    public void shutdown() {
        nettyProcessor.shutdown();
        nettyHttpServer.shutdown();
        nettyHttpClient.shutdown();
    }
}
